#    Copyright 2011 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPIP.
#    COOPIP is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPIP is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPIP.  If not, see <http://www.gnu.org/licenses/>.

#************************BEGIN Add Include Files to Path************************
import sys
IncludePath="/var/coopip/djangoproject/include"
if(not IncludePath in sys.path):
    sys.path.append(IncludePath)


    
#************************END   Add Include Files to Path************************
from django.contrib.gis.geos import *
import os, time, psycopg2, datetime

#********************Setup psycopg2 and django section********************
PathDjangoRoot="/opt/coopip/"
if(not PathDjangoRoot in sys.path):
    sys.path.append(PathDjangoRoot)
from django.core.management import setup_environ
import djangoproject.settings
setup_environ(djangoproject.settings)
from djangoproject.models import *
from django.contrib.gis.geos import GEOSGeometry
import CIS, AMR, OMS, GIS
from django.contrib.gis.db import models
#********************Setup psycopg2 and django section********************
from django.db import transaction

import urllib
import httplib
import OMS, datetime
import COOPIP_Misc
import datetime
import time


def PingNearbyMeterIfConditionsMet(meter):
    if(not COOPIP_Misc.MakeSureNotTooManyPendingMeterPings(meter.Substation)):
        return
    Now = datetime.datetime.now()
    SecondsSinceLastPingAttempt = (Now - meter.LastPingOutDateTime).total_seconds()
    if(SecondsSinceLastPingAttempt > 900):  
        print "Pinging:  " + str(meter)
        meter.SendPingToAMRIndicator=True
        meter.save()



@transaction.commit_on_success
def ImportIncidents():
    OMSIncidents=OMS.ImsIncident.objects.all()
    OMSIncidentDict={}  #Key = record_id, Value = [Status, OutageType, MeterNumber, MapNumber]

    for i in OMSIncidents:
        if(CurrentOMSIncident.objects.filter(Recordid=str(i.record_id))):
            Current = CurrentOMSIncident.objects.filter(Recordid=str(i.record_id))[0]
            PingNearbyMeters = False
        else:
            Current = CurrentOMSIncident()
            Current.Recordid = str(i.record_id)
            PingNearbyMeters = True #This is a new record, so ping nearby meters
        
        OMSIncidentDict[str(i.record_id)] = [i.incident_id, i.status, i.outage_type, str(i.meter_number).strip().lstrip('0'), str(i.map_location).strip().lstrip('0')]
        Current.Incidentid = OMSIncidentDict[str(i.record_id)][0]
        Current.Status = OMSIncidentDict[str(i.record_id)][1]
        Current.OutageType = OMSIncidentDict[str(i.record_id)][2]
        Current.MeterNumber = OMSIncidentDict[str(i.record_id)][3]
        Current.MapNumber = OMSIncidentDict[str(i.record_id)][4]
        GISMeter=GIS.Coopgissymbologymeter.objects.filter(mapnumber=OMSIncidentDict[str(i.record_id)][3])
        if(GISMeter):
            Current.Point = GISMeter[0].the_geom
        Current.save()
        Current.CreateLog()
        meter = Meter.objects.filter(SerialNumber=Current.MeterNumber)
        if(meter):
            meter = meter[0]
            meter.CalculateIncidentSymbology()
            if(datetime.datetime.now() - meter.LastPingOutDateTime).total_seconds() > (60 * 30):  #If has not been pinged in the past 30 minutes, unconditionally ping
                meter.SendPingToAMRIndicator=True
                meter.save()
                meter.CalculateIncidentSymbology()
        MaxMetersToPing =  30
        MeterPingCount = 0
        
        if(meter and PingNearbyMeters):
            NearbyMeters=Meter.objects.filter(Point__distance_lte=(meter.Point, 5280)).filter(AMRCircuitName=meter.AMRCircuitName).order_by('LastPingOutDateTime')
            for nearbyMeter in NearbyMeters:
                PingNearbyMeterIfConditionsMet(nearbyMeter)
                MeterPingCount = MeterPingCount + 1
                if(MeterPingCount > MaxMetersToPing):
                    break

    COOPIPOMSIncidents = CurrentOMSIncident.objects.all()
    for i in COOPIPOMSIncidents:
        if(str(i.Recordid) in OMSIncidentDict.keys()):
            continue
        else:
            MeterNumber = i.MeterNumber
            meter = Meter.objects.filter(SerialNumber=MeterNumber)
            i.delete()
            if(meter):
                meter[0].CalculateIncidentSymbology()


    



Start = datetime.datetime.now()
SecondsElapsed = (Start - datetime.datetime.now()).total_seconds()
while(SecondsElapsed < 60):
    ImportIncidents()
    time.sleep(15)
    SecondsElapsed = (datetime.datetime.now() - Start).total_seconds()
